
function parseLrcTime(timeStr) {
  if (!timeStr) {
    return;
  }
  var timeArr = timeStr.split(':');
  const m = parseInt(timeArr[0]);
  const s = parseInt(timeArr[1]);
  return m * 60 + s;
}

function parseLrc() {
  var lrcList = []
  var lrcData = lrc.split('\n');

  var len = lrcData.length;
  for (var i = 0; i < len; i++) {
    var itemStrToArr = lrcData[i].split(']');
    var lrcItem = {
      time: parseLrcTime(itemStrToArr[0].substring(1)),
      words: itemStrToArr[1]
    };

    lrcList.push(lrcItem)
  }

  return lrcList;
}

var doms = {
  audio: document.querySelector('.el-audio'),
  container: document.querySelector('.el-container'),
  lrcList: document.querySelector('.lrc-list')
}

function createLrcDom() {
  var len = lrcData.length;
  var liFragments = document.createDocumentFragment();
  for (i = 0; i < len; i++) {
    var li = document.createElement('li');
    li.classList.add('lrc-list__item');
    li.textContent = lrcData[i].words;
    liFragments.appendChild(li)
  }
  doms.lrcList.appendChild(liFragments)
}


var lrcData = parseLrc() // 解析歌词

createLrcDom() // 创建歌词dom

function getLrcIndex(currentTime) {
  var len = lrcData.length;
  for (var i = 0; i < len; i++) {
    if (lrcData[i].time > currentTime) {
      return i - 1;
    }
  }
  return len - 1;
}

var containerHeight = doms.container.clientHeight
var ulHeight = doms.lrcList.clientHeight
var liHight = doms.lrcList.children[0].clientHeight
var maxOffsetHeight = ulHeight - containerHeight
var minOffsetHeight = 0

function setOffset() {
  var index = getLrcIndex(doms.audio.currentTime)
  console.log(index);

  var oh = index * liHight - containerHeight / 2 + liHight / 2
  if (oh < minOffsetHeight) {
    oh = minOffsetHeight
  } else if (oh > maxOffsetHeight) {
    oh = maxOffsetHeight
  }
  // doms.lrcList.style.transform = 'translateY(' + -oh + 'px)'
  doms.lrcList.style.transform = `translateY(${-oh}px)`

  var li = document.querySelector('.lrc-list__item.active')
  if (li) {
    li.classList.remove('active')
  }
  var liNew = doms.lrcList.children[index]
  if (liNew) {
    liNew.classList.add('active')
  }
}

doms.audio.addEventListener('timeupdate', setOffset)